import {Component, ViewEncapsulation, Input} from '@angular/core';
import {FormGroup, AbstractControl, FormBuilder, Validators} from '@angular/forms';
import {UserService} from '../../../../services/app.user';
import {BaThemeSpinner}  from '../../../../theme/services';
import {EmailValidator}  from '../../../../theme/validators';
import {Utility} from '../../../../services/app.utility';
import {Country} from '../../../../services/country';
import {AuthenticationHelper} from '../../../../app.authentication';
import {Constants} from '../../../../common/app.constants';
import {Router}       from '@angular/router';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'AddUser',
    encapsulation: ViewEncapsulation.None,
    templateUrl: './addUser.html',
    styleUrls: ['./addUser.scss'],
    providers: [Country]
})

export class AddUser {
    @Input()
    constants:Constants;
    public form:FormGroup;
    public inputFullName:AbstractControl;
    public inputEmail:AbstractControl;
    public inputPassword:AbstractControl;
    public inputReEnterPassword:AbstractControl;
    public inputAddress:AbstractControl;
    public inputCity:AbstractControl;
    public inputState:AbstractControl;
    public inputCountry:AbstractControl;
    public inputAboutMe:AbstractControl;
    public inputIsAdmin:AbstractControl;
    public inputVersioning:AbstractControl;
    public inputGender:AbstractControl;
    public countries:any;
    public passwordRow:any;
    public editUserButton:any;
    public editUserInformation:any;
    public userId:any;
    public isAdminStatus:any;
    public versionDescription:any;
    public showViewDiv:any;
    public userPrevData:any;
    public userNewData:any;
    public start:any;
    public end:any;
    public check:any;

    constructor(private userService:UserService, private formGroups:FormBuilder, private router:Router, private authentication:AuthenticationHelper, private spinner:BaThemeSpinner, private utility:Utility, private  country:Country) {
        this.constants = new Constants();
        // Set form group data and validation
        this.form = formGroups.group({
            'inputFullName': ['', Validators.compose([Validators.required])],
            'inputEmail': ['', Validators.compose([Validators.required, EmailValidator.validate])],
            'inputPassword': ['', Validators.compose([Validators.required])],
            'inputReEnterPassword': ['', Validators.compose([Validators.required])],
            'inputAddress': ['', []],
            'inputCity': ['', []],
            'inputState': ['', []],
            'inputCountry': ['', []],
            'inputAboutMe': ['', []],
            'inputIsAdmin': ['', []],
            'inputVersioning': ['', [Validators.compose([Validators.required, Validators.minLength(4)])]],
            'inputGender': ['', []]
        });

        this.start = 0;
        this.check = 0;

        // start timer function call
        this.startCount();

        // Function for get user data to check current version of user
        this.getUserData();

        this.passwordRow = true;
        this.editUserButton = true;
        this.isAdminStatus = false;
        this.showViewDiv = false;
        this.inputFullName = this.form.controls['inputFullName'];
        this.inputEmail = this.form.controls['inputEmail'];
        this.inputPassword = this.form.controls['inputPassword'];
        this.inputReEnterPassword = this.form.controls['inputReEnterPassword'];
        this.inputAddress = this.form.controls['inputAddress'];
        this.inputCity = this.form.controls['inputCity'];
        this.inputState = this.form.controls['inputState'];
        this.inputCountry = this.form.controls['inputCountry'];
        this.inputAboutMe = this.form.controls['inputAboutMe'];
        this.inputIsAdmin = this.form.controls['inputIsAdmin'];
        this.inputVersioning = this.form.controls['inputVersioning'];
        this.inputGender = this.form.controls['inputGender'];
        this.countries = this.country.country;
        this.clearFormData();

        // condition for check user edited data
        if (this.utility.checkEditUser) {
            this.setEditUserData(this.utility.editUser);
        }

        // condition for set user country and gender
        if (this.router.url === '/admin/addUser') {
            this.editUserButton = true;
            this.passwordRow = true;
            this.clearFormData();
            this.inputGender.setValue('Male');
            this.inputCountry.setValue('Hong Kong');
        }

        // Call version API function
        this.getVersionsDescription();
    }

    // Function for get version data
    public getVersionsDescription() {
        this.userService.getAllVersion({}).subscribe(
            data => this.getVersionSucces(data),
            error => this.getVersionFail(error)
        );
    }

    // Function for get version data successfully
    public getVersionSucces(result) {
        let newData = [];
        for (let a = 0; a < result.length; a++) {
            if (result[a].isLocked === false) {
                newData.push(result[a]);
            }
        }

        this.versionDescription = newData;
    }

    // Function for get version data fail
    public getVersionFail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    // Function for set edit data to form
    public setEditUserData(data) {
        this.userPrevData = data;
        this.passwordRow = false;
        this.editUserButton = false;
        this.userId = data._id;
        this.inputFullName.setValue(data.name);
        this.inputEmail.setValue(data.email);
        this.inputAddress.setValue(data.address);
        this.inputCity.setValue(data.city);
        this.inputState.setValue(data.state);
        this.inputCountry.setValue(data.country);
        this.inputAboutMe.setValue(data.aboutMe);
        this.inputIsAdmin.setValue(data.isAdmin);
        this.inputVersioning.setValue(data.version);
        this.inputGender.setValue(data.gender);
    }

    // Function for add new user data API call
    public addNewUser(values) {
        let fullName = values.inputFullName.trim();
        let inputData:any;
        inputData = {
            name: fullName,
            email: values.inputEmail,
            address: values.inputAddress,
            city: values.inputCity,
            state: values.inputState,
            country: values.inputCountry,
            aboutMe: values.inputAboutMe,
            isAdmin: values.inputIsAdmin,
            versioning: values.inputVersioning,
            gender: values.inputGender
        };
        if (inputData.name !== '') {
            if (this.editUserInformation) {
                inputData._id = this.userId;
                this.spinner.showProgress();
                inputData.role = this.userPrevData.role;
                this.userService.editUser(inputData).subscribe(
                    data => this.editUserSucces(data),
                    error => this.registerFail(error)
                );
            } else {
                inputData.password = values.inputPassword;
                inputData.passwordConfirm = values.inputReEnterPassword;

               if (this.form.valid) {
                    this.spinner.showProgress();
                    this.userService.addUser(inputData).subscribe(
                        data => this.registerSucces(data),
                        error => this.registerFail(error)
                    );
                }
            }
        } else {
            toastr.error('Enter user name');
        }
    }

    // Function for edit user data successfully
    public editUserSucces(result) {
        this.userNewData = result;
        this.spinner.hideProgress();
        toastr.success('Edit user successfully');
        this.clearFormData();
        this.router.navigate(['admin/user']);
    }

    // Function for register user success
    public registerSucces(result) {
        toastr.success('Added new user successfully');
        this.clearFormData();
        this.spinner.hideProgress();
        this.router.navigate(['admin/user']);
        let event = {
            'target': 'true'
        };
        this.onTypeEvent(event);
    }

    // Function for register user fail
    public registerFail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error.message);
    }

    // Function for check user status
    public getDataAdminStatus() {
        this.isAdminStatus = true;
    }

    // Function for clear add user data form
    public clearFormData() {
        this.form.reset();
    }

    // Function for call API check user profile
    public getUserData() {
        this.userService.userProfile({}).subscribe(
            data => this.userProfilesucces(data),
            error => this.userProfilefail(error));
    }

    // Function for check user is superadmin or not
    public  userProfilesucces(data) {
        if (data.profile.role.indexOf('superadmin') >= 0) {
            this.showViewDiv = true;
        }
    }

    // Function for check user fail
    public userProfilefail(error) {
        this.spinner.hideProgress();

    }

    // User log for keystroke event
    public onTypeEvent(event) {

        if (event.target === 'true') {
            let input = {
                'target': 'Filled form add new user',
                'action': 'keystroke'
            };
            this.userService.setUserLogs(input).subscribe(
                data => this.logSuccessKey(data),
                error => {
                });
        }

    }

    // User log for keystroke event success
    public logSuccessKey(data) {
        let input = {
            'target': this.constants.URL + 'admin/user',
            'value': 'user',
            'action': 'redirect'
        };
        this.userService.setUserLogs(input).subscribe();
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

      // API call for tract navigation sequence
      let seq = {
        sequence: {
          "pageName": 'admin/addUser',
          "timeSpent": this.start
        }

      };
      this.userService.setUrlSeq(seq).subscribe();

    }

    // Function call after view for log API
    ngAfterViewChecked() {
        let self = this;
        $('.createNewUser').unbind().mousedown(function (event) {
            self.checkAllLogs(event);
        });
    }

    // Function for check all logs
    public checkAllLogs(event) {
        let self = this;
        let buttons;
        if (event.button === 0) {
            buttons = 'left click';
        } else if (event.button === 1) {
            buttons = 'roller click';
        } else {
            buttons = 'right click';
        }
        let domTarget = event.target;
        let domTargetString = domTarget.toString();
        let stringDemo = domTargetString.substr(12, 25);
        let index = stringDemo.indexOf('E');
        let dom = stringDemo.substr(0, index);
        let text = $(event.target).unbind().text();


        let input = {
            'target': dom + ' ' + text,
            'value': text,
            'action': buttons
        };

        self.setUserLogs(input);
    }

    // Function for call API for log
    public setUserLogs(input) {

        this.userService.setUserLogs(input).subscribe();

        if (input.value.indexOf('Add New User') >= 0) {
            let data = {
                'target': this.constants.ADDUSER,
                'value': 'admin/adduser',
                'action': 'redirect'
            };

            this.userService.setUserLogs(data).subscribe();
        } else if (input.value.indexOf('Edit User') >= 0) {
            let data = {
                'target': this.constants.URL + 'admin/user',
                'value': 'admin/user',
                'action': 'redirect'
            };

            this.userService.setUserLogs(data).subscribe();
        } else if (input.value.indexOf('Submit') >= 0) {
            let data = {
                'target': this.constants.URL + 'listidea',
                'value': 'listidea',
                'action': 'redirect'
            };

            this.userService.setUserLogs(data).subscribe();
        }
    }

}
